package vip.meeet.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class ConsumerTest {

    public static final String ADDRESS_COLLECTION = "127.0.0.1:9092";
    public static final String CONSUMER_TOPIC = "test_topic";
    public static final String CONSUMER_GROUP_ID = "test_group";
    /**
     * 是否自动提交
     */
    public static final String CONSUMER_ENABLE_AUTO_COMMIT = "true";
    public static final String CONSUMER_AUTO_COMMIT_INTERVAL_MS = "1000";
    /**
     * 连接超时时间
     */
    public static final String CONSUMER_SESSION_TIMEOUT_MS = "30000";
    /**
     * 每次获取消息条数
     */
    public static final int CONSUMER_MAX_POLL_RECORDS = 10;
    /**
     * 获取数据超时时间
     */
    public static final Duration CONSUMER_POLL_TIME_OUT = Duration.ofMillis(3000);

    private static KafkaConsumer<String,String> consumer;
    
    static {
        Properties configs = initConfig();
        consumer = new KafkaConsumer<String, String>(configs);
        consumer.subscribe(Arrays.asList(CONSUMER_TOPIC));
    }

    private static Properties initConfig(){
        Properties props = new Properties();
        props.put("bootstrap.servers", ADDRESS_COLLECTION);
        props.put("group.id", CONSUMER_GROUP_ID);
        props.put("enable.auto.commit", CONSUMER_ENABLE_AUTO_COMMIT);
        props.put("auto.commit.interval.ms", CONSUMER_AUTO_COMMIT_INTERVAL_MS);
        props.put("session.timeout.ms", CONSUMER_SESSION_TIMEOUT_MS);
        props.put("max.poll.records", CONSUMER_MAX_POLL_RECORDS);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", StringDeserializer.class.getName());
        props.put("value.deserializer", StringDeserializer.class.getName());
        return props;
    }

    public static void main(String[] args) {
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(CONSUMER_POLL_TIME_OUT);
            records.forEach((ConsumerRecord<String, String> record)->{
                System.out.println("revice: key ==="+record.key()+" value ===="+record.value()+" topic ==="+record.topic());
            });
        }
    }
}

